package org.uni.cil.crm;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.PipedInputStream;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.uni.cil.benchmark.*;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.content.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import javax.servlet.jsp.JspWriter;
/**
 * @author Elmar
 * 
 */

public class CRMConnector implements Runnable {
	/**
	 * @param args
	 */
	

	public InputStream pi = null;
	public String provider;
	private Benchmark benchmarker = null;
	public JspWriter writer;
	
	public CRMConnector(PipedInputStream writeIn, Benchmark uploadBenchmarker, String crmProvider, JspWriter writer) {
		this.pi = writeIn;
		this.benchmarker = uploadBenchmarker;
		this.writer = writer;
		this.provider = crmProvider;
	}
	
	public void postMail() {
		// TODO Auto-generated method stub
		// create the http client
		// create the post method with the uri of the pia demo server
		HttpClient client = this.getClient();
		HttpPost post = this.getPost();
		
		// Formatting output
		DecimalFormat sizeFormat = new DecimalFormat("###.##");
		DecimalFormat timeFormat = new DecimalFormat("###.###");
		try {
			ObjectInputStream oi = new ObjectInputStream(pi);
				
			int i = 1;
			String message = null;
			while((message = (String) oi.readObject()) != null)
			{
		    	StringEntity entity = null;
				String body = message;
				
				entity = new StringEntity(body);
				
				post.setEntity(entity);
				writer.println("<tr><td><b>"+ i +"</td>");
				long start = System.currentTimeMillis();
				benchmarker.start();
				if (i != 14){
				HttpResponse response = client.execute(post);
				String resStr = "<div class='imgholder'><img src='images/fail.png' title='Failed' alt='' /></div>";
				String res = "failed";
				Header[] headerLoc = response.getHeaders("Location");
				String url ="";
				if (response.getStatusLine().getStatusCode() == 201)
				{
					url = headerLoc[0].getValue();
					url="<A href='"+ url + "'>"+url+"</A>";
					resStr = "<div class='imgholder'><img src='images/succes2.png' title='Successful' alt='' /></div>";
					res = "success";
				}
				benchmarker.stop((i) + "Mail:" + res, body.getBytes().length);
				writer.print("<td>"+url+"</b></td>");
				long stop =  System.currentTimeMillis();
				String mailSize = sizeFormat.format(body.getBytes().length / 1024.0);
				writer.println("<td>"+ mailSize + " kB</td>");
				String time = timeFormat.format(((stop-start)/1000.0));
				writer.println("<td>"+ time + " sec</td>");
				writer.println("<td>");
				writer.println(resStr);
				writer.println("</td></tr>");
				writer.flush();
				EntityUtils.consume(response.getEntity());
				}
				i++;
				message = "";
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
		}		
		
		//benchmarker.toCSV();
	}
	
	private HttpPost getPost () {
		HttpPost post = null;
		if (this.provider == "CASPIA") {
			post = new HttpPost(
					"http://piademos.cas.de/pia/rest/v3.0/type/emailstore/file");
		}
		return post;
	}
	private HttpClient getClient(){
		HttpClient client = null;
		if (this.provider == "CASPIA") {
			client = new DefaultHttpClient();
	
			// set the credentials necessary for the cas pia authentication
			((AbstractHttpClient) client).getCredentialsProvider().setCredentials(
					new AuthScope(AuthScope.ANY),
	//				new AuthScope("cas", 80),
					new UsernamePasswordCredentials("cil/Robert Glaser",
							"9638?Phone"));
		
		}
		return client;
	}
	
	@Override
	public void run() {
		this.postMail();
		benchmarker.toCSV();
	}
}
